﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using Assist;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Electrical;
using Autodesk.Revit.UI;
using YArchitech.LIB;
using YArchitech.Revit;
using HYCodeBase.WinForm;
using HYElectricDim;
using YRevitJig;
using YJKRGeometry;
using HYView;

namespace ElectricDim
{
	[Regeneration(RegenerationOption.Manual)]
	[Transaction(TransactionMode.Manual)]
	public class CmdWireLoopDim : IExternalCommand
	{
		public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
		{
			UIApplication application = commandData.Application;
			UIDocument activeUIDocument = application.ActiveUIDocument;
			Document document = activeUIDocument.Document;
			if (!(document.ActiveView is ViewPlan))
			{
				Result result = SwitchView.SetUsableView((CmdViewType)3, commandData);
				if (result != Result.Succeeded)
				{
					return result;
				}
			}
			ElectricalUtils.ViewValidating(document);
			WindowHandle windowHandle = null;
			if (windowHandle == null)
			{
				windowHandle = new WindowHandle(Process.GetCurrentProcess().MainWindowHandle);
			}
			DlgWireLoopDim instance = DlgWireLoopDim.GetInstance(commandData.Application, windowHandle);
			instance.Show(windowHandle);
			double num = (double)document.ActiveView.Scale;
			new SubTransaction(activeUIDocument.Document);
			for (;;)
			{
				Transaction transaction = new Transaction(document, "LayLabel");
				try
				{
					transaction.Start();
					string pathName = Path.Combine(Product.DataLocation, "YArchitech Electric Shared Parameters.txt");
					string gropeName = "电气数据";
					List<string> listStr = new List<string>
					{
						"回路编号"
					};
					YJKRevitTools.SetInstanceParameter(application, pathName, gropeName, listStr, BuiltInCategory.OST_Wire, true);
					Reference reference = activeUIDocument.Selection.PickObject((Autodesk.Revit.UI.Selection.ObjectType)1, new WireFilter());
					Element element = document.GetElement(reference);
					if (element != null)
					{
						XYZ xyz = new XYZ(reference.GlobalPoint.X, reference.GlobalPoint.Y, document.ActiveView.SketchPlane.GetPlane().Origin.Z);
						try
						{
							ElementIdDate elementIdDate = Assist.ExtensibleStorageManager.ReadFromElement<ElementIdDate>(element, this.guid);
							if (elementIdDate.GetId().IntegerValue != 0)
							{
								document.Delete(elementIdDate.GetId());
							}
						}
						catch
						{
						}
						ElectricalUtils.DeleteTagOfElement(document, element as Wire, "导线回路标记");
						if (instance.GetLabelType() == LabelType.FromText)
						{
							Parameter parameter = element.GetParameter("回路编号");
							if (parameter != null)
							{
								parameter.Set(instance.Label);
							}
						}
						Autodesk.Revit.DB.ElementType elementType = instance.GetElementType();
						ElementSet elementSet = new ElementSet();
						Autodesk.Revit.DB.Group group = null;
						if (elementType != null)
						{
							ElectricDimJig electricDimJig = new ElectricDimJig(activeUIDocument);
							if (instance.GetDimStyle() == LeaderStyle.Orthogonal)
							{
								electricDimJig.ResetPoint = XUiJigBase.EResetPoint.eByOrtho;
							}
							electricDimJig.RectWidth = AssistFunc.mmToFeet(8.0) * num;
							electricDimJig.RectHeight = AssistFunc.mmToFeet(4.0) * num;
							XYZ xyz2 = electricDimJig.PickDimPoint(xyz, ElectricDimJig.EDimType.eBottomCorner, "请拾取标注点:");
							electricDimJig.Dispose();
							if (xyz2 == null || xyz2.DistanceTo(xyz) < 0.005)
							{
								transaction.RollBack();
								break;
							}
							IndependentTag independentTag = RevitVersionFuncs.NewTag(document, document.ActiveView, new Reference(element), false, 0, 0, xyz2);
							independentTag.ChangeTypeId(elementType.Id);
							LeaderStyle dimStyle = instance.GetDimStyle();
							if (dimStyle == LeaderStyle.HasLeader || dimStyle == LeaderStyle.Orthogonal)
							{
                                independentTag.LeaderEndCondition = (LeaderEndCondition)1;
								BoundingBoxXYZ boundingBoxXYZ = independentTag.get_BoundingBox(document.ActiveView);
								XYZ xyz3 = new XYZ(boundingBoxXYZ.Min.X, boundingBoxXYZ.Min.Y, xyz.Z);
								double num2 = 0.5;
								XYZ ePoint;
								if (Geometry.LessThan(xyz2.X, xyz.X))
								{
									ePoint = new XYZ(2.0 * boundingBoxXYZ.Min.X - boundingBoxXYZ.Max.X - 1.0, boundingBoxXYZ.Min.Y, xyz.Z);
									num2 = 2.0 * boundingBoxXYZ.Min.X - boundingBoxXYZ.Max.X - xyz2.X - 0.5;
								}
								else
								{
									ePoint = new XYZ(boundingBoxXYZ.Max.X + 1.0, boundingBoxXYZ.Min.Y, xyz.Z);
								}
								DetailLine detailLine = YJKRevitTools.DrawDetailLine(document, xyz, xyz3);
								DetailLine detailLine2 = YJKRevitTools.DrawDetailLine(document, xyz3, ePoint);
								elementSet.Insert(detailLine);
								elementSet.Insert(detailLine2);
								if (instance.GetDimLinkStyle() == PointStyle.Line)
								{
									Line curve = ElectricalUtils.PromtLine(reference.GlobalPoint, element as Wire);
									XYZ xyz4 = (curve.GetEndPoint(1) - curve.GetEndPoint(0)).Normalize();
									xyz4 = new XYZ(xyz4.X, xyz4.Y, 0.0);
									(xyz3 - xyz).Normalize();
									int num3 = ElectricalUtils.Quadrant(xyz, xyz2);
									double num4;
									if (num3 == 1 || num3 == 3)
									{
										num4 = 2.3561944901923448 + xyz4.AngleOnPlaneTo(XYZ.BasisX, XYZ.BasisZ);
									}
									else
									{
										num4 = 0.78539816339744828 + xyz4.AngleOnPlaneTo(XYZ.BasisX, XYZ.BasisZ);
									}
									DetailLine detailLine3 = YJKRevitTools.DrawDetailLine(document, xyz, xyz + xyz4);
									DetailLine detailLine4 = YJKRevitTools.DrawDetailLine(document, xyz, xyz - xyz4);
									Line line = Line.CreateBound(xyz, new XYZ(xyz.X, xyz.Y, xyz.Z + 1.0));
									ElementTransformUtils.RotateElement(document, detailLine3.Id, line, num4);
									ElementTransformUtils.RotateElement(document, detailLine4.Id, line, num4);
									elementSet.Insert(detailLine3);
									elementSet.Insert(detailLine4);
								}
								group = document.CreatYJKGroup(elementSet);
								ElementTransformUtils.MoveElement(document, independentTag.Id, new XYZ(num2, 0.0, 0.0));
							}
						}
						transaction.Commit();
						if (instance.rbInput.Checked && instance.rbAutoAdd1.Checked)
						{
							instance.Label = instance.AutoAddLoopNum(instance.Label, 1);
						}
						if (group != null && group.IsValidObject)
						{
							ElementIdDate obj = new ElementIdDate(group.Id);
							Assist.ExtensibleStorageManager.WriteToElement(element, this.guid, obj);
						}
						continue;
					}
					transaction.RollBack();
				}
				catch (Exception)
				{
					instance.Close();
					transaction.RollBack();
					return Autodesk.Revit.UI.Result.Succeeded;
				}
				break;
			}
			instance.Close();
			return Autodesk.Revit.UI.Result.Succeeded;
		}

		private Guid guid = new Guid("356cda5a-e6c5-4c2f-a9ef-b1113131b8c8");
	}
}
